package blue.txt.handle;

import java.io.File;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

import blue.txt.model.FileModel;
import blue.txt.util.FileModelUtil;

/**
 * TXT文件处理器
 * 
 * @author zhengj
 * @since 1.0 2017年7月4日
 */
public class TxtFileHandler implements FileHandler
{
	private ContentParser chapterParser;
	private ContentParser contentParser;
	
	public TxtFileHandler()
	{
	}

	@Override
	public void handle(File file, String dir)
	{
		if (chapterParser == null || contentParser == null)
			throw new IllegalArgumentException("缺少内容解析器");
		
		AtomicInteger atomic = new AtomicInteger(1);
		FileModel model = null;
		try (Scanner scanner = new Scanner(file, "UTF-8"))
		{
			System.out.println("开始解析：" + file.getAbsolutePath());
			while (scanner.hasNextLine())
			{
				String line = scanner.nextLine();
				if (line == null || line.isEmpty())
					continue;
				line = FileModelUtil.trim(line);
				if (line.isEmpty())
					continue;
				
				FileModel m = chapterParser.parse(line, null, atomic);
				if (m != null)
				{
					m.printFileName();
					FileModelUtil.save(dir, model);
					
					model = m;
				}
				else
				{
					model = contentParser.parse(line, model, atomic);
				}
			}
			if (model != null)
			{
				FileModelUtil.save(dir, model);
			}
				
			System.out.println("解析完成：" + file.getAbsolutePath());
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void setChapterParser(ContentParser parser)
	{
		this.chapterParser = parser;
	}

	@Override
	public void setContentParser(ContentParser parser)
	{
		this.contentParser = parser;
	}
	
	

	
}
